package com.online.findagentserver.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by littleheng on 2018/4/27
 */
@Configuration
@MapperScan(basePackages = "com.online.findagentserver.slave1", sqlSessionTemplateRef = "slave1SqlSessionTemplate")
public class OlsMod1DatasourceConfig {
    @Bean(name = "slave1DataSourceProperties")
    @Qualifier("slave1DataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.ols1")
    public DataSourceProperties slave1DataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * 配置数据数据源 ols1
     *
     * @return
     */
    @Bean(name = "slave1Datasource")
    @ConfigurationProperties(prefix = "spring.datasource.ols1")
    public DataSource slave1Datasource() {

        //return DataSourceBuilder.create().build();
        return slave1DataSourceProperties().initializeDataSourceBuilder().build();
    }

    /**
     * 配置session工厂
     *
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "slave1SqlSessionFactory")
    public SqlSessionFactory slave1SqlSessionFactory(@Qualifier("slave1Datasource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
//        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:"));
        return bean.getObject();
    }

    /**
     * 配置事务管理器
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "slave1TransactionManger")
    public DataSourceTransactionManager slave1TransactionManger(@Qualifier("slave1Datasource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    /**
     * 模版
     *
     * @param sqlSessionFactory
     * @return
     * @throws Exception
     */
    @Bean(name = "slave1SqlSessionTemplate")
    public SqlSessionTemplate slave1SqlSessionTemplate(@Qualifier("slave1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}